package com.intelligent.util;

import io.jsonwebtoken.*;
import java.util.Date;

public class AppJwtUtil {

    // 过期时间：7天
    private static final long EXPIRE = 1000 * 60 * 60 * 24 * 7;
    // 加密密钥
    private static final String SECRET = "intelligent_erp";

    /**
     * 生成Token
     */
    public static String getToken(Long userId) {
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject(userId.toString())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
    }

    /**
     * 解析Token获取用户ID
     */
    public static Long getUserId(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
            return Long.valueOf(claims.getSubject());
        } catch (Exception e) {
            return null;
        }
    }
}
